/*
 * @Description:菜单基本信息
 * @Author: wangfuwei
 * @Date: 2020-12-08 00:26:40
 * @LastEditors: wangfuwei
 * @LastEditTime: 2021-04-25 23:10:44
 * @FilePath: /horizon-frontend/src/store/modules/menu.js
 */
import Vue from "vue";
import { getLockedApps, getMenus, getCloudApps } from "@/api/system";
import { MENUS, ACTIVE_APP, CLOUD_APPS } from "@/store/mutation-types";
import { dynamicI18n } from "@/locales/util";

const menu = {
  namespaced: true,
  state: {
    globalApps: [
      //全局应用
      {
        fdId: "sys_index",
        code: "index",
        global: true,
        home: "index",
      },
      {
        fdId: "sys_apps",
        code: "apps",
        global: true,
        home: "apps",
      },
    ],
    lockedApps: [], //用户已锁定应用
    menus: {}, //应用下的菜单(缓存)
    activeApp: "", //当前激活应用
    cloudApps: [], //用户拥有权限的应用 cloud -> apps
    appMaps: {}, //用户拥有权限的应用 { appCode:{ app } }
  },
  mutations: {
    [MENUS]: (state, { menus, appCode }) => {
      Vue.set(state.menus, appCode, menus);
      dynamicI18n(menus);
    },
    [ACTIVE_APP]: (state, appCode) => {
      state.activeApp = appCode;
    },
    [CLOUD_APPS]: (state, { cloudApps = [], lockedApps = [] }) => {
      state.cloudApps = cloudApps;
      dynamicI18n(state.cloudApps);
      cloudApps.forEach(cloud => cloud.children.forEach(app => (state.appMaps[app.code] = app)));

      //用户锁定的应用（过滤掉无权限的应用）
      lockedApps.forEach(appCode => {
        const app = state.appMaps[appCode];
        if (app) {
          app.locked = true;
          state.lockedApps.push(app);
        }
      });
    },
  },
  actions: {
    //激活应用
    active({ commit, state }, appCode) {
      return (async () => {
        commit(ACTIVE_APP, appCode);

        let menus = null;
        if (state.menus[appCode]) {
          //缓存中获取菜单
          menus = state.menus[appCode];
        } else if (!state.globalApps.some(app => app.code === appCode)) {
          //非全局应用，请求应用下菜单
          menus = await getMenus(appCode).then(menus => {
            commit(MENUS, { menus, appCode });
            return menus;
          });
        }

        return menus;
      })();
    },

    //用户拥有权限的应用
    getCloudApps({ commit }) {
      return (async () => {
        const cloudApps = await getCloudApps();
        const lockedApps = await getLockedApps();
        commit(CLOUD_APPS, { cloudApps, lockedApps });
      })();
    },
  },
};

export default menu;
